package com.example.routes

import com.example.data.model.*
import com.example.service.ASMRService
import com.example.service.UserService
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.util.pipeline.*
import kotlin.collections.set

suspend fun PipelineContext<*, ApplicationCall>.checkAdmin() {
    val principal = call.principal<JWTPrincipal>()
    val type = principal!!.payload.getClaim("type").asString()
    if (type != "管理员") {
        call.respond(ManagementResponse("非管理员，无权限访问", false, null))
    }
}

fun Route.adminRouting(
    userService: UserService, asmrService: ASMRService
) {
    authenticate {
        route("admin") {
            get("count") {
                checkAdmin()
                val type = call.parameters["type"] ?: return@get
                //代表数据集合的下一行有数据
                val row: MutableMap<String, Any> = HashMap() //模拟一条数据
                var count = 0L
                var name = ""
                when (type) {
                    "user" -> {
                        name = "用户数量"
                        count = userService.count()
                    }

                    "asmr" -> {
                        name = "ASMR数量"
                        count = asmrService.asmrCount()
                    }

                    "tag" -> {
                        name = "分类数量"
                        count = asmrService.tagCount()
                    }

                    "audio" -> {
                        name = "音频数量"
                        count = asmrService.audioCount()
                    }
                }
                row["name"] = name
                row["count"] = count
                call.respond(ManagementResponse(type, true, row))
            }
            get("user") {
                checkAdmin()
                val action = call.parameters["action"] ?: return@get
                when (action) {
                    "list" -> {
                        val t = userService.allUser(
                            call.parameters["page"]?.toInt() ?: return@get,
                            call.parameters["limit"]?.toInt() ?: return@get,
                            param("username")
                        )
                        call.respond(
                            ManagementResponse("", true, t, t.size)
                        )
                    }

                    "get" -> call.respond(
                        ManagementResponse.success(
                            userService.getUser(
                                call.parameters["id"]?.toInt() ?: return@get
                            )
                        )
                    )

                    "add" -> {
                        val username = call.parameters["username"] ?: return@get
                        val password = call.parameters["password"] ?: return@get
                        val login = userService.isExist(
                            LoginDTO(username, password)
                        )
                        if (login != null) {
                            call.respond(Response("添加失败，该用户名已存在", false, null))
                        } else {
                            val b = userService.addUser(
                                UserForAdmin(
                                    0,
                                    username,
                                    password,
                                    call.parameters["status"].toBoolean()
                                )
                            )
                            call.respond(if (b) ManagementResponse.success("添加成功") else ManagementResponse.fail("添加失败"))
                        }
                    }

                    "edit" -> {
                        val b = userService.editUser(
                            UserForAdmin(
                                call.parameters["id"]?.toInt() ?: return@get,
                                call.parameters["username"] ?: return@get,
                                call.parameters["password"] ?: return@get,
                                call.parameters["status"].toBoolean()
                            )
                        )
                        call.respond(if (b) ManagementResponse.success("修改成功") else ManagementResponse.fail("修改失败"))
                    }

                    "delete" -> {
                        val b = userService.deleteUser(call.parameters["id"]?.toInt() ?: return@get)
                        call.respond(if (b) ManagementResponse.success("删除成功") else ManagementResponse.fail("删除失败"))
                    }

                    "deleteAll" -> {
                        val ids = call.parameters["ids"]?.split(",") ?: return@get
                        var b: Boolean = false
                        ids.forEach {
                            b = userService.deleteUser(it.toInt())
                        }
                        call.respond(if (b) ManagementResponse.success("删除成功") else ManagementResponse.fail("删除失败"))
                    }
                }
            }
            get("asmr") {
                checkAdmin()
                val action = call.parameters["action"] ?: return@get
                when (action) {
                    "list" -> {
                        val t = asmrService.getAll(
                            call.parameters["page"]?.toInt() ?: return@get,
                            call.parameters["limit"]?.toInt() ?: return@get,
                            param("title")
                        )
                        call.respond(ManagementResponse("", true, t, t.size))
                    }

                    "titleList" -> {
                        val t = asmrService.getAllASMRIdTitle()
                        call.respond(ManagementResponse("", true, t, t.size))
                    }

                    "get" -> call.respond(
                        ManagementResponse.success(
                            asmrService.getASMR(
                                call.parameters["id"]?.toInt() ?: return@get
                            )
                        )
                    )

                    "add" -> {
                        val b = asmrService.addASMR(
                            ASMRForAdmin(
                                intParam("id") ?: return@get,
                                param("title") ?: return@get,
                                param("img"),
                                param("img240"),
                                param("name"),
                                intParam("rateCount") ?: 0,
                                floatParam("rateAverage") ?: 0f,
                                param("createDate") ?: "",
                                param("cv"),
                                null,
                            ), param("tags")
                        )
                        call.respond(if (b) ManagementResponse.success("添加成功") else ManagementResponse.fail("添加失败"))
                    }

                    "edit" -> {
                        val b = asmrService.editASMR(
                            ASMRForAdmin(
                                intParam("id") ?: return@get,
                                param("title") ?: return@get,
                                param("img"),
                                param("img240"),
                                param("name"),
                                intParam("rateCount") ?: 0,
                                floatParam("rateAverage") ?: 0f,
                                param("createDate") ?: "",
                                param("cv"),
                                null,
                            ), param("tags")
                        )
                        call.respond(if (b) ManagementResponse.success("修改成功") else ManagementResponse.fail("修改失败"))
                    }

                    "delete" -> {
                        val b = asmrService.deleteASMR(call.parameters["id"]?.toInt() ?: return@get)
                        call.respond(if (b) ManagementResponse.success("删除成功") else ManagementResponse.fail("删除失败"))
                    }

                    "deleteAll" -> {
                        val ids = call.parameters["ids"]?.split(",") ?: return@get
                        var b = false
                        ids.forEach {
                            b = asmrService.deleteASMR(it.toInt())
                        }
                        call.respond(if (b) ManagementResponse.success("删除成功") else ManagementResponse.fail("删除失败"))
                    }
                }
            }
            get("tag") {
                checkAdmin()
                val action = call.parameters["action"] ?: return@get
                when (action) {
                    "list" -> {
                        val t = asmrService.getTags(
                            call.parameters["page"]?.toInt() ?: return@get,
                            call.parameters["limit"]?.toInt() ?: return@get,
                            param("name")
                        )
                        call.respond(ManagementResponse("", true, t, t.size))
                    }

                    "get" -> call.respond(
                        ManagementResponse.success(
                            asmrService.getTag(
                                call.parameters["id"]?.toInt() ?: return@get
                            )
                        )
                    )

                    "add" -> {
                        val b = asmrService.addTag(param("name") ?: return@get)
                        call.respond(if (b) ManagementResponse.success("添加成功") else ManagementResponse.fail("添加失败"))
                    }

                    "edit" -> {
                        val b = asmrService.editTag(param("name") ?: return@get, intParam("id") ?: return@get)
                        call.respond(if (b) ManagementResponse.success("修改成功") else ManagementResponse.fail("修改失败"))
                    }

                    "delete" -> {
                        val b = asmrService.deleteTag(call.parameters["id"]?.toInt() ?: return@get)
                        call.respond(if (b) ManagementResponse.success("删除成功") else ManagementResponse.fail("删除失败"))
                    }

                    "deleteAll" -> {
                        val ids = call.parameters["ids"]?.split(",") ?: return@get
                        var b = false
                        ids.forEach {
                            b = asmrService.deleteTag(it.toInt())
                        }
                        call.respond(if (b) ManagementResponse.success("删除成功") else ManagementResponse.fail("删除失败"))
                    }
                }
            }
            get("audio") {
                checkAdmin()
                val action = call.parameters["action"] ?: return@get
                when (action) {
                    "list" -> {
                        val t = asmrService.getAllDetail(
                            call.parameters["page"]?.toInt() ?: return@get,
                            call.parameters["limit"]?.toInt() ?: return@get,
                            intParam("asmrId"),
                            param("title")
                        )
                        call.respond(ManagementResponse("", true, t, t.size))
                    }

                    "add" -> {
                        val b = asmrService.addDetail(
                            ASMRDetail(
                                0,
                                intParam("asmrId") ?: return@get,
                                param("title") ?: return@get,
                                param("url") ?: return@get,
                            )
                        )
                        call.respond(if (b) ManagementResponse.success("添加成功") else ManagementResponse.fail("添加失败"))
                    }

                    "edit" -> {
                        val b = asmrService.editDetail(
                            ASMRDetail(
                                intParam("id") ?: return@get,
                                intParam("asmrId") ?: return@get,
                                param("title") ?: return@get,
                                param("url") ?: return@get,
                            )
                        )
                        call.respond(if (b) ManagementResponse.success("修改成功") else ManagementResponse.fail("修改失败"))
                    }

                    "delete" -> {
                        val b = asmrService.deleteDetail(call.parameters["id"]?.toInt() ?: return@get)
                        call.respond(if (b) ManagementResponse.success("删除成功") else ManagementResponse.fail("删除失败"))
                    }

                    "deleteAll" -> {
                        val ids = call.parameters["ids"]?.split(",") ?: return@get
                        var b = false
                        ids.forEach {
                            b = asmrService.deleteDetail(it.toInt())
                        }
                        call.respond(if (b) ManagementResponse.success("删除成功") else ManagementResponse.fail("删除失败"))
                    }
                }
            }
        }
    }
}

fun PipelineContext<*, ApplicationCall>.param(name: String) = call.parameters[name]

fun PipelineContext<*, ApplicationCall>.intParam(name: String) = call.parameters[name]?.toIntOrNull()

fun PipelineContext<*, ApplicationCall>.floatParam(name: String) = call.parameters[name]?.toFloatOrNull()
